<template>
  <el-dialog
    v-bind="$attrs"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    v-on="$listeners"
    @open="onOpen"
    fullscreen
    lock-scroll
    class="jsbos-full-dialog"
    :show-close="false"
    :modal="false"
    append-to-body
  >
    <div id="qrcode" ref="qrCode" v-show="false"></div>
    <div class="jsbos-full-dialog-header">
      <div class="header-title">
        <img src="@/assets/images/jsbos.png" class="header-logo" />
        <p class="header-txt">· 打印预览</p>
      </div>
      <div class="options">
        <el-button type="primary" size="small" @click="word"
          >Word下载</el-button
        >
        <el-button type="primary" size="small" @click="print">打印</el-button>
        <el-button @click="closeDialog()">{{
          $t("common.cancelButton")
        }}</el-button>
      </div>
    </div>
    <div class="main" v-loading="loading">
      <div ref="tsPrint" class="print-content" v-html="printTemplate" />
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import { getData } from "@/api/system/printDev";
import QRCode from "qrcodejs2";
import JsBarcode from "jsbarcode";
export default {
  props: ["id", "formId", "fullName"],
  computed: {
    ...mapGetters(["userInfo"]),
  },
  data() {
    return {
      data: {},
      printTemplate: "",
      recordList: [],
      loading: false,
    };
  },
  methods: {
    //设置条形码和二维码
    setSrc() {
      //二维码
      var qrcodeList = document.querySelectorAll(".qrcode");

      qrcodeList.forEach((el, idx) => {
        //  console.log(el.getAttribute("src"));

        let text = el.getAttribute("alt");
        // let imgarr = text.split('.')
        // if (imgarr.length > 1) {    //是否多层级
        //   // console.log(text.split('.'))

        //   text =

        // }

        let div = document.createElement("div");
        // console.log("text", text);
        let qrcode = new QRCode(div, {
          width: 265,
          height: 265, // 高度
          text: text, // 二维码内容
          // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
          // background: '#f0f'
          // foreground: '#ff0'
          correctLevel: QRCode.CorrectLevel.H, //容错级别 容错级别有：（1）QRCode.CorrectLevel.L （2）QRCode.CorrectLevel.M （3）QRCode.CorrectLevel.Q （4）QRCode.CorrectLevel.H
        });

        function getNowSrc() {
          setTimeout(() => {
            let nowSrc = div.getElementsByTagName("img")[0].getAttribute("src");
            // console.log("nowSrc", nowSrc);
            if (nowSrc) {
              el.src = nowSrc;
              // null
              div = null;
            } else {
              getNowSrc();
            }
          }, 50);
        }
        getNowSrc();
      });

      //条形码

      var barcodeList = document.querySelectorAll(".barcode");
      barcodeList.forEach((el, idx) => {
        var text = el.getAttribute("alt");
        el.id = "barcode" + idx;
        // console.log(text);
        JsBarcode(`#barcode${idx}`, text, {
          // format: "pharmacode",
          // lineColor: "#0aa",
          width: 4,
          height: 80,
          displayValue: false,
        });
      });
    },
    onOpen() {
      if (!this.id) return;
      this.printTemplate = "";
      this.data = {};
      this.loading = true;
      let query = {
        id: this.id,
        formId: this.formId,
      };
      getData(query).then((res) => {
        // console.log("res===========>", query, res, res.data.printTemplate);
        if (!res.data) return;

        this.printTemplate = res.data.printTemplate;

        this.data = res.data.printData;
        this.recordList = res.data.operatorRecordList || [];
        this.$nextTick(() => {
          setTimeout(() => {
            this.setSrc();
          }, 100);

          const tableList = this.$refs.tsPrint.getElementsByTagName("table");
          if (tableList.length) {
            for (let j = 0; j < tableList.length; j++) {
              const tableObj = tableList[j];
              let tds = [];
              let newTable = [];
              for (let i = 0; i < tableObj.rows.length; i++) {
                tds = tableObj.rows[i];
                const dataTag = this.isChildTable(tds.cells);
                if (dataTag) {
                  this.retrieveData(dataTag, tableObj, tds, newTable);
                } else {
                  newTable.push(tds);
                }
              }

              tableObj.getElementsByTagName("tbody")[0].innerHTML = "";
              for (let i = 0; i < newTable.length; i++) {
                tableObj
                  .getElementsByTagName("tbody")[0]
                  .appendChild(newTable[i]);
              }
            }
          }
        });
        this.replaceValue(this.data);
        this.replaceSysValue();
        this.loading = false;
      });
    },
    isChildTable(cells) {
      let tableName = "";

      outer: for (let j = 0; j < cells.length; j++) {
        const cell = cells[j];
        let spanList = cells[j].getElementsByTagName("span");

        if (!spanList.length) break outer;
        let hasChildTable = false;
        inner: for (let j = 0; j < spanList.length; j++) {
          const spanEle = spanList[j];
          const dataTag = spanEle.getAttribute("data-tag")
            ? spanEle.getAttribute("data-tag").split(".")[0]
            : "null";
          if (dataTag && dataTag !== "null") {
            hasChildTable = true;
            tableName = dataTag;
            break inner;
          }
        }
        if (hasChildTable) break outer;
      }
      return tableName;
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    shengchengtable(data, tds, Keytext, index) {
      console.log("data", data, tds, Keytext, index);
      console.log(tds.cells);
      for (let j = 0; j < tds.cells.length; j++) {
        console.log(tds.cells[j].getElementsByClassName("img-word"));
        if (tds.cells[j].getElementsByClassName("img-word").length > 0) {
          if (
            data.item_result.includes(".jpg") ||
            data.item_result.includes(".png") ||
            data.item_result.includes(".jpeg")
          ) {
            tds.cells[j].getElementsByClassName("img-word")[0].innerHTML = "";
            JSON.parse(data.item_result) &&
              JSON.parse(data.item_result).forEach((item) => {
                tds.cells[j].getElementsByClassName(
                  "img-word"
                )[0].innerHTML += `<img class="" style="float: right;" src="${
                  window.location.origin + window.location.pathname + item.url
                }"  width="79" height="79" alt="图片&文本显示"/>`;
              });
          } else {
            tds.cells[j].getElementsByClassName("img-word")[0].innerHTML =
              data.item_result;
          }
        }
      }
      // console.log(document.getElementsByClassName("img-word")[index], "----");

      // if (data.item_type == 3) {
      //   // console.log(JSON.parse(data.item_result), "+++++++");
      //   tds.document.getElementsByClassName(
      //     "img-word"
      //   )[0].innerHTML = `<img class="" style="float: right;" src="${
      //     "https://gl.bringspring.com/jsbos-logistics-web" +
      //     JSON.parse(data.item_result)[0].url
      //   }"  width="79" height="79" alt="图片&文本显示"/>`;
      // } else {
      //   tds.document.getElementsByClassName("img-word")[0].innerHTML = "2222";
      // }

      // console.log(document.getElementsByClassName("img-word")[index]);
      // console.log("tds", tds);
      // console.log("Keytext", Keytext);
      //  增加Keytext 参数，防止获取错误
      for (let key in data) {
        for (let j = 0; j < tds.cells.length; j++) {
          //  console.log('tds', tds, tds.cells[j])
          let spanList = tds.cells[j].getElementsByTagName("span");
          //获取里面的qrcodeList 和
          let qrcodeList = tds.cells[j].getElementsByClassName("qrcode");
          let barcodeList = tds.cells[j].getElementsByClassName("barcode");
          // console.log(imgWordList, "imgWordList++++++");
          //  console.log('qrcodeList', qrcodeList, barcodeList)

          for (let i = 0; i < spanList.length; i++) {
            if (`{${key}}` === spanList[i].innerHTML) {
              spanList[i].innerHTML = data[key];
            }
          }
          // setAttribute
          //替换 alt 内容
          //二维码处理
          for (let i = 0; i < qrcodeList.length; i++) {
            let altText = qrcodeList[i].getAttribute("alt");
            altText = altText.substring(1, altText.length - 1);
            let altArr = altText.split(".");

            if (
              altArr.length > 1 &&
              Keytext == altArr[altArr.length - 2] &&
              `${key}` === altArr[altArr.length - 1]
            ) {
              qrcodeList[i].setAttribute("alt", data[key]);
            }
          }
          //条形码处理
          for (let i = 0; i < barcodeList.length; i++) {
            let altText = qrcodeList[i].getAttribute("alt");
            altText = altText.substring(1, altText.length - 1);
            let altArr = altText.split(".");
            if (
              altArr.length > 1 &&
              Keytext == altArr[altArr.length - 2] &&
              `${key}` === altArr[altArr.length - 1]
            ) {
              barcodeList[i].setAttribute("alt", data[key]);
            }
          }

          //图片处理
          // for (let i = 0; i < imgWordList.length; i++) {
          //   // console.log(imgWordList[i]);
          //   let altText = imgWordList[i].getAttribute("src");
          //   console.log(altText, i, "+-+-+——+-+");
          //   // altText = altText.substring(1, altText.length - 1);
          //   // let altArr = altText.split(".");
          //   // if (
          //   //   altArr.length > 1 &&
          //   //   Keytext == altArr[altArr.length - 2] &&
          //   //   `${key}` === altArr[altArr.length - 1]
          //   // ) {
          //   //   imgWordList[i].setAttribute("alt", data[key]);
          //   // }
          // }
        }
      }
      // console.log('tds==========>', tds)
      return tds;
    },

    retrieveImg() {},
    retrieveData(dataTag, tableObj, tds, newTable) {
      for (let key in this.data) {
        if (key == dataTag) {
          for (let j = 0; j < this.data[key].length; j++) {
            newTable.push(
              this.shengchengtable(
                this.data[key][j],
                tds.cloneNode(true),
                key,
                j
              )
            );
            console.log(document.getElementsByClassName("img-word")[j], "----");
          }
        }
      }
    },
    replaceSysValue() {
      // console.log(this.printTemplate, "-------");
      const recordList = this.recordList.filter(
        (o) => o.handleStatus == 0 || o.handleStatus == 1
      );
      const systemPrinter =
        this.userInfo.userName + "/" + this.userInfo.userAccount;
      const systemPrintTime = this.jsbos.toDate(new Date());
      let systemApprovalContent = "";
      if (recordList.length) {
        systemApprovalContent +=
          '<table style="border-collapse: collapse; width: 100%;" border="1" data-mce-style="border-collapse: collapse; width: 100%;"><tbody><tr><td style="width:30%;" data-mce-style="width: 30%;">审批节点</td><td style="width: 70%;" data-mce-style="width: 70%;">审批内容</td></tr>';
        let content = "";
        for (let i = 0; i < recordList.length; i++) {
          const record = recordList[i];
          let desc =
            (record.userName || record.handleId) +
            "于" +
            this.jsbos.toDate(record.handleTime) +
            (record.handleStatus == 1 ? "审批通过" : "审批拒绝") +
            (record.handleOpinion ? "，审批意见：" + record.handleOpinion : "");
          content += `<tr><td style="width: 30%;" data-mce-style="width: 30%;"><span class="wk-print-tag-wukong wk-tiny-color--common" contenteditable="false">${record.nodeName}</span></td><td style="width: 70%;" data-mce-style="width: 70%;"><span class="wk-print-tag-wukong wk-tiny-color--common" contenteditable="false">${desc}</span></td></tr>`;
        }
        systemApprovalContent += content;
        systemApprovalContent += "</tbody></table>";
      }
      this.printTemplate = this.replaceAll(
        this.printTemplate,
        "{systemPrinter}",
        systemPrinter
      );
      this.printTemplate = this.replaceAll(
        this.printTemplate,
        "{systemPrintTime}",
        systemPrintTime
      );
      this.printTemplate = this.replaceAll(
        this.printTemplate,
        "{systemApprovalContent}",
        systemApprovalContent
      );
    },
    replaceValue(data) {
      console.log(data);
      for (let key in data) {
        this.printTemplate = this.replaceAll(
          this.printTemplate,
          `{${key}}`,
          data[key] || ""
        );
        if (Array.isArray(data[key]) && data[key] && data[key].length) {
          this.replaceValue(data[key]);
        }
      }
    },
    replaceAll(data, replace, value) {
      const lenr = replace.length;
      const len = data.length;
      let newData = "";
      let i = 0;
      for (i; i < len; i++) {
        let k = 0;
        let string = "";

        for (k; k < lenr; k++) {
          var n = i + k;
          string += data[n];
        }
        if (string === replace) {
          newData += value;
          i = i + lenr;
        }
        newData += data[i];
      }

      // console.log("data", newData);

      return newData;
    },
    word() {
      let print = this.$refs.tsPrint.innerHTML;
      const blob = new Blob([print], {
        type: "",
      });
      const name = this.fullName ? `${this.fullName}.doc` : "下载文档.doc";
      this.downloadFile(blob, name);
    },
    downloadFile(data, name, type) {
      let blob = new Blob([data], {
        type: type || "",
      });
      let downloadElement = document.createElement("a");
      let href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = name;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    },
    print() {
      let print = this.$refs.tsPrint.innerHTML;
      let newWindow = window.open("_blank");
      newWindow.document.body.innerHTML = print;
      newWindow.print();
      newWindow.close();
    },
  },
};
</script>
<style lang="scss" scoped>
.print-content {
  background: white;
  padding: 40px 30px;
  margin: 0 auto;
  border-radius: 4px;
  width: 600px;
  height: 100%;
  overflow: auto;
}
</style>
